package Observer.InterfacesImpl;

import Observer.Interfaces.Observer;
import Observer.Interfaces.Subject;

import java.util.ArrayList;
import java.util.List;

/**
 * 主题的具体实现
 * @Author: pengzx
 * @Description:
 * @Date: 16:02 2017/9/5
 * @Modified by: 1.0
 */
public class WeatherData implements Subject {
    /**
     * observerList用来保存注册的观察者
     */
    private List<Observer> observerList;

    private float temp;
    private float humidity;
    private float pressure;

    public WeatherData()
    {
        observerList = new ArrayList<Observer>(0);
    }

    @Override
    public void RegisterObserver(Observer observer)
    {
        /**
         * 当观察者注册的时候添加进去就好
         */
        observerList.add(observer);
    }

    @Override
    public void RemoveObserver(Observer observer)
    {
        /**
         * 移除观察者对象
         */
       int i = observerList.indexOf(observer);
       if (i >=0){
           observerList.remove(i);
       }
    }

    @Override
    public void notifyObservers()
    {
        for (int i=0,j=observerList.size();i<j;i++){
            Observer observer = observerList.get(i);
            observer.update(temp,humidity,pressure);
        }
    }

    /**
     * 当数据改变通知观察者
     */
    public void measurementsChanged(){
        notifyObservers();
    }

    public void  setMeasurements(float temp,float humidity,float pressure){
        this.temp = temp;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
